﻿Imports System.Data.OleDb

Partial Public Class AddDiscussion
    Inherits System.Web.UI.Page

    Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
        
    End Sub

    Protected Sub btn_AddDiscussion_Click(ByVal sender As Object, ByVal e As EventArgs) Handles btn_AddDiscussion.Click
        Dim conn = New OleDbConnection(ConfigurationManager.ConnectionStrings("PlacesConnectionString").ToString())

        Dim addDiscussionSQL As String = "INSERT INTO discussionforum(Topic,Body,Category_fkid,StartedBy) VALUES(@Topic,@Body,@Category_fkid,@StartedBy)"

        'Dim fileLocationOnServer = Request.MapPath("Images/Discussion/" & f_DiscussionImage.FileName)

        'f_DiscussionImage.SaveAs(fileLocationOnServer)

        'Dim relativePath As String = "Images/Discussion/" & f_DiscussionImage.FileName


        Dim dbcmd = New OleDbCommand(addDiscussionSQL, conn)

        dbcmd.Parameters.AddWithValue("@Topic", tb_DiscussionTitle.Text)
        dbcmd.Parameters.AddWithValue("@Body", tb_DiscussionBody.Text)
        dbcmd.Parameters.AddWithValue("@Category_fkid", dropDown_DiscussionCategories.SelectedValue)
        'dbcmd.Parameters.AddWithValue("@Tags", tb_discussionTags.Text)
        'dbcmd.Parameters.AddWithValue("@Picture", relativePath)
        dbcmd.Parameters.AddWithValue("@StartedBy", User.Identity.Name)
        conn.Open()
        dbcmd.ExecuteNonQuery()
        addDiscussionToUser(User.Identity.Name, getLastDiscussionAdded())
        conn.Close()
        Response.Redirect("discussionforum.aspx")
    End Sub

    Sub addDiscussionToUser(ByVal UserName As String, ByVal discussionId As Integer)
        Dim conn = New OleDbConnection(ConfigurationManager.ConnectionStrings("PlacesConnectionString").ToString())
        Dim sql As String = "INSERT INTO UserDiscussionJunction (UserName, Discussion_fkid) VALUES (@UserName, @Discussion_fkid)"
        Dim cmd As New OleDbCommand(sql, conn)
        cmd.CommandType = CommandType.Text
        conn.Open()
        cmd.Parameters.AddWithValue("@UserName", UserName)
        cmd.Parameters.AddWithValue("@Discussion_fkid", discussionId)
        cmd.ExecuteNonQuery()
        conn.Close()
    End Sub

    Function getLastDiscussionAdded() As Integer
        Dim conn = New OleDbConnection(ConfigurationManager.ConnectionStrings("PlacesConnectionString").ToString())
        Dim sql As String = "SELECT TOP 1 ID FROM discussionforum ORDER BY ID DESC"
        Dim cmd As OleDbCommand = New OleDbCommand(sql, conn)
        conn.Open()
        Dim dbread = cmd.ExecuteReader()
        dbread.Read()
        Dim returnVal = dbread("ID")
        conn.Close()
        Return returnVal
    End Function
End Class